const db = require('../../db/index')
const encryPassword = require('../../utils/password')
const uuid = require('uuid')
const {generToken,verifyToken} = require('../../auth/token')
const {randomName} = require('../../utils/randomNickName')
const {del} = require("express/lib/application");

exports.register = (req,res) => {
    let {userName,userPassword,userType} = req.body
    if(userName !== '' && userPassword !== ''){
        let _encryPassword = encryPassword(userPassword)
        let userParty = randomName()
        userType = userType ? userType * 1 : 0
        console.log('加密之后的密码',_encryPassword)
        let insertSql = "insert into users(userName,userPassword,userParty,userType) values(?,?,?,?)"
        db.query(insertSql,[userName,_encryPassword,userParty,userType],(err,result) => {
            if(err) {
                // console.log(err)
                if(err.sqlState == '23000') {
                    res.send({
                        code:400,
                        message:'用户名已存在'
                    })
                    return
                }
                res.send({code:400,message:err.sqlMessage})
                return
            }
            console.log('插入成功',result)
            res.send({
                code:200,
                message:'注册成功'
            })
        })
        return
    }
    res.send({
        code:400,
        message:'您输入的数据格式不正确'
    })
}

exports.login = (req,res) => {
    let {userName,userPassword} = req.body
    if(userName !== '' && userPassword !== ''){
        let selectSql = "select * from users where  userName = ?"
        db.query(selectSql,[userName],(err,result) =>{
            if(err) {
                console.log('登录错误',err)
                res.send({
                    code:400,
                    message:err.sqlMessage
                })
                return
            }
            if(result.length === 0) return res.send({code:400,message:'用户名错误'})
            let _encryPassword = encryPassword(userPassword)
            if(_encryPassword === result[0].userPassword) {
                let token = generToken(result[0].userId)
                console.log('解密token出来的信息',verifyToken(token))
                // 删除用户的密码
                delete result[0]['userPassword']
                let userInfo = result[0]
                    res.send({
                    code:200,
                    message:'登录成功',
                    token: 'Bearer ' +token,
                    userInfo
                })
            }else {
                res.send({
                    code:400,
                    message:'密码或用户名输入错误',
                })
            }
            // console.log('用户信息',result)
        })
        return
    }
    res.send({
        code:400,
        message:'登录失败'
    })
    return;
}


/**
 * @description 查询用户列表
 * orderS 0 降序 1升序 desc 降序 asc 升序 默认降序
 * orderType 默认按照注册时间
 * orderType 0 == 'registerTime' 按照注册时间排序
 * orderType 1 == 'userParty' 按照昵称进行排序
 * */
exports.userList = (req,res) => {
    let {pageSize,pageNo,orderType,orderS} = req.query
    console.log(pageSize,pageNo,orderType,orderS)
    if(pageSize && pageNo) {
        pageSize = pageSize*1
        pageNo = pageNo*1
        let start = ( pageNo - 1 ) * pageSize
        let end = pageSize
        let _orderType,_orderS
        _orderS = orderS ? orderS == '0' ? 'ASC' : 'DESC' : 'ASC' // 有的话根据 0 1 进行排序 升降 没有的话默认是降序
        orderType = orderType == undefined ? orderType : '0'
        if(orderType == '0') {_orderType = 'registerTime'}
        if(orderType == '1') {_orderType = 'userParty'}
        let selectSql = `SELECT userId,userIp,userName,userParty,userEmail,userAvatar,userType,registerTime,userBirthday,userAge,(SELECT COUNT(*) from users) as total_count from users ORDER BY ${_orderType} ${_orderS} LIMIT ${start},${end}`
        let count = 0
        let list = []
        console.log('查询语句',selectSql)
        db.query(selectSql,(err,result) => {
            if(err) res.send({code:400,message:err.sqlMessage})
            if(result.length!== 0) {
                count = result[0].total_count
                result.forEach(item => delete item["total_count"])
            }
            res.send({
                code:200,message:'查询成功',count,list:result
            })
            return
        })
        return;
    }
    res.send({
        code:400,
        message:'查询用户列表失败'
    })
    return
}

//删除对应的用户
exports.deleteUser = (req,res) => {
    let {userId} = req.params
    if(userId) {
        try {
            let deleteSql = "delete from users where userId = ?"
            db.query(deleteSql,[userId],(err,result) => {
                // console.log('resut',result)
                if(err) return res.send({ code:400,message:err.sqlMessage })
                if(result.affectedRows == 1) {
                    res.send({
                        code:200,
                        message:'删除成功'
                    })
                }else {
                    res.send({code:400,message:'未找到当前用户,或已被删除,请刷新后重试'})
                }
            })
        }catch (e) {
            return res.send({code:400,message:e.message})
        }
        return
    }
    res.send({code:400,message:'未查询到当前用户'})
}
